package com.zhxl.model.test;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Repository;

import com.zhxl.model.Internal.User;
@Repository(value="queryContextDaoImpl")
public class QueryContextDaoImpl{
	/*
	 * 	java.lang.IllegalArgumentException: 'sessionFactory' or 'hibernateTemplate' is required
	 */
	@Autowired
	ApplicationContext con;
	private HibernateTemplate hibernateTemplate;
	SessionFactory sessionFactory;
	//@Autowired
	//@Qualifier(value="sessionFactory")
//	public void setSessionFactory(SessionFactory sessionFactory) {
//		this.sessionFactory = sessionFactory;
//	}
//	public SessionFactory getSessionFactory() {
//		return sessionFactory;
//	}
//	
//	public SessionFactory getSelfSessionFactory() {
//		return sessionFactory;
//	}
	//@Autowired
	//HibernateTemplate hibernateTempleate;
	/**
	 *  Cannot convert value of type [java.lang.String] to required type [org.hibernate.SessionFactory] for property 'sessionFactory': no matching editors or conversion strategy found
	 */
	
//	public SessionFactory getSessionFactory() {
//		return sessionFactory;
//	}
//	public void setSessionFactory(SessionFactory sessionFactory) {
//		this.sessionFactory = sessionFactory;
//	}
	
	
	
	public Session getSession(){
		return sessionFactory.openSession();
	}
	@SuppressWarnings("unchecked")
	public List<User> getContext() {
		System.out.println(hibernateTemplate==null);
		List<User> users = new ArrayList<User>();
		
		System.out.println(getSession()==null);
		Session session = getSession();
		/**
		 * 使用Session session = getSessionFactory().getCurrentSession();报错Could not obtain transaction-synchronized
		 */
		//could not open connect access denied for user 
		//username or password 错误
		
		Transaction transaction = session.beginTransaction();
		/*
		 * 下面写法报错nested transactions not supportedat org.
		 * 事务嵌套异常
		 */
		//session.beginTransaction().begin();
		//session.beginTransaction().begin();
		User u = null;
		u = (User) session.get(User.class, "12");
		/**
		 * from user其中user一定要与model的entity name值一致
		 */
		
		if(users.size()>0){
			return users;
		}
		String name = u.getName();
		System.out.println(name);
		transaction.commit();
		if(u == null){
			users = session.createQuery("from user").list();
		}
		users.add(u);
		return users;
	}
}
